<template>
  <div class="ad-chart-w">
    <Title>
      <template #content>
        <p class="title">广告共享情况</p>
      </template>
    </Title>
    <div class="type-w">
      <a-radio-group type="button" v-model="dateDimension" @change="refreshData">
        <a-radio value="DAY">按日</a-radio>
        <a-radio value="WEEK">按周</a-radio>
        <a-radio value="MONTH">按月</a-radio>
      </a-radio-group>
    </div>
    <div class="flex" style="margin-top: 20px">
      <ul>
        <li class="all-target" v-for="(target, i) in allTargetKeys" :key="i">
          <p>
            <span>{{ target.name }}</span>
            <span v-if="target.type == 'price'">({{ currencySymbol[searchParams.currencyCode] }})</span>
            <a-popover v-if="target.tip" :content="target.tip">
              <icon-question-circle />
            </a-popover>
          </p>
          <p class="value">
            <span class="value-price" v-if="target.type == 'percentage'">{{ formatVal(target, 'value') }}%</span>
            <span class="value-price" v-else>{{ formatVal(target, 'value') }}</span>
            <span>{{ ['acos', 'impressions', 'clicks', 'purchasesOrder', 'saleAmount'].includes(target.key) ? '总计' : '平均' }}</span>
          </p>
          <div class="price-item flex-c">
            <span class="label">环比</span>
            <span class="val" v-if="target.type == 'percentage'">{{ formatVal(target, 'monValue') }}%</span>
            <span class="val" v-else>{{ formatVal(target, 'monValue') }}</span>
            <template v-if="Number($extract(targetMap[target.key], 'monComparedValue')) > 0">
              <icon-caret-up style="color: rgb(var(--success-5))" />
              <span class="diff" style="color: rgb(var(--success-5))">{{ $extract(targetMap[target.key], 'monComparedValue') }}%</span>
            </template>
            <template v-else>
              <icon-caret-down style="color: rgb(var(--danger-5))" />
              <span class="diff" style="color: rgb(var(--danger-5))">{{ $extract(targetMap[target.key], 'monComparedValue') }}%</span>
            </template>
          </div>
        </li>
      </ul>
      <a-spin class="chart-w" :loading="loading" style="width: 100%; height: 350px">
        <div ref="contributionBoardChartRef" style="height: 350px"></div>
      </a-spin>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import Title from '@/views/index/components/Title.vue'
  import useEcharts from '@/hooks/useEcharts'
  import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue'
  import { getOverallTrendCharts } from '@/api/advert'
  import { dispose } from 'echarts/core'
  import useAdvertStore from '@/store/modules/advert'
  import { currencySymbol } from '@/utils/globalData'
  const props = defineProps({
    searchParams: {
      type: Object,
      default: () => {},
    },
    targetMap: {
      type: Object,
      default: () => {},
    },
  })

  const loading = ref(false)
  const advertStore = useAdvertStore()
  const chartDatas = ref<Array<any>>([])
  const dateDimension = ref('DAY')
  const targetList = ref<any>({
    saleAmount: {
      key: 'saleAmount',
      name: '店铺销售额',
      type: 'price',
      color: '#73c0de',
    },
    asots: {
      key: 'asots',
      name: 'ASoTS',
      tip: '广告销售额占店铺销售额的比例，广告销售额占比=广告销售额/店铺销售额100%',
      type: 'percentage',
      color: '#91cc75',
    },
    acots: {
      key: 'acots',
      tip: '广告花费占店铺销售额的比例，广告花费占比=广告花费/店铺销售额100%',
      name: 'ACoTS',
      type: 'percentage',
      color: '#ee6666',
    },
  })
  const allTargetKeys = ref<Array<any>>(Object.values(targetList.value))

  // 数量多以万为单位
  function formatVal(item: any, key: string) {
    let val = props.targetMap[item.key]?.[key] || 0
    if (val < 100000) {
      return Number(val)
    } else {
      return Number(val / 10000).toFixed(2) + '万'
    }
  }

  // 刷新数据
  async function refreshData() {
    await getChartData()
    nextTick(() => {
      initChart()
    })
  }

  // 获取所有指标图表数据
  let dates: Array<any> = []
  let yDataMap = {}

  async function getChartData() {
    if (!props.searchParams.startDate) return
    loading.value = true
    const res: any = await getOverallTrendCharts({
      ...props.searchParams,
      dateDimension: dateDimension.value,
    })
    loading.value = false
    chartDatas.value = res?.data || []
    dates = chartDatas.value.map((el) => el.date)
    Object.keys(targetList.value).forEach((key) => {
      yDataMap[key] = chartDatas.value.map((el) => Number(el[key]))
    })
  }
  const contributionBoardChartRef = ref<HTMLDivElement | null>(null)

  // 获取series轴信息
  function setSeries() {
    let list = allTargetKeys.value?.map((item, index) => {
      return {
        name: item.name,
        yAxisIndex: index,
        type: 'line',
        data: yDataMap[item.key],
        color: targetList.value[item.key]?.color,
      }
    })
    return list
  }
  // 获取Y轴信息
  function setYData() {
    return allTargetKeys.value?.map((item: any) => {
      let max = Math.max.apply(null, yDataMap[item.key] || [])
      return {
        type: 'value',
        name: targetList.value[item.key]?.name,
        min: 0,
        offset: item.key == 'acots' ? 50 : 0,
        max: setMaxInterval(max).max,
        splitNumber: 5,
        minInterval: 1,
        nameGap: 20,
        interval: setMaxInterval(max).interval,
        axisLine: {
          show: true,
          lineStyle: {
            color: targetList.value[item.key]?.color,
          },
        },
        axisLabel: {
          formatter(v: any) {
            v = v.toString()
            if (Math.abs(v) >= 100000) {
              return v / 10000 + '万'
            } else {
              return v
            }
          },
        },
      }
    })
  }
  // 为了平均分布Y轴
  function setMaxInterval(max: number) {
    if (max <= 1) {
      return { max: 1, interval: 0.2 }
    }
    if (max <= 5) {
      return { max: 5, interval: 1 }
    }
    if (max <= 10) {
      return { max: 10, interval: 2 }
    }
    if (max <= 50) {
      return { max: 50, interval: 10 }
    }
    if (max <= 100) {
      return { max: 100, interval: 20 }
    }
    if (max <= 500) {
      return { max: 500, interval: 100 }
    }
    if (max <= 1000) {
      return { max: 1000, interval: 200 }
    }
    if (max <= 2000) {
      return { max: 2000, interval: 400 }
    }
    if (max <= 5000) {
      return { max: 5000, interval: 1000 }
    }
    if (max <= 8000) {
      return { max: 8000, interval: 1600 }
    }
    if (max <= 10000) {
      return { max: 10000, interval: 2000 }
    }
    if (max <= 20000) {
      return { max: 20000, interval: 4000 }
    }
    if (max <= 50000) {
      return { max: 50000, interval: 10000 }
    }
    if (max <= 80000) {
      return { max: 80000, interval: 16000 }
    }
    if (max <= 100000) {
      return { max: 100000, interval: 20000 }
    }
    if (max <= 500000) {
      return { max: 500000, interval: 100000 }
    }
    if (max <= 1000000) {
      return { max: 1000000, interval: 200000 }
    }
    if (max <= 2000000) {
      return { max: 2000000, interval: 400000 }
    }
    if (max <= 5000000) {
      return { max: 5000000, interval: 1000000 }
    }
    if (max <= 10000000) {
      return { max: 10000000, interval: 2000000 }
    }
    if (max <= 50000000) {
      return { max: 50000000, interval: 10000000 }
    }
    return {
      max: Math.ceil(max / 5) * 5,
      interval: Math.ceil(max / 5),
    }
  }
  function initChart() {
    // 容易导致重复渲染，先清除
    if (contributionBoardChartRef.value) {
      dispose(contributionBoardChartRef.value as HTMLDivElement)
    }
    if (!advertStore.targetClickKeys?.length) return
    const option = {
      grid: {
        left: 50,
        top: 40,
        bottom: 50,
        right: 50,
        containLabel: true,
      },
      tooltip: {
        trigger: 'axis',
        valueFormatter: (v: number) => {
          if (Math.abs(v) >= 100000) {
            return (v / 10000).toFixed(2) + '万'
          } else {
            return v
          }
        },
      },
      legend: {
        data: setSeries().map((el: any) => el.name),
        bottom: '0px',
      },
      xAxis: {
        type: 'category',
        data: dates,
        axisLine: {
          show: true,
          lineStyle: {
            color: '#98A3B2',
            width: 0,
            type: 'solid',
          },
        },
        axisTick: {
          show: false,
        },
      },
      yAxis: setYData(),
      series: setSeries(),
    }
    nextTick(() => useEcharts(contributionBoardChartRef.value as HTMLDivElement).setOption(option))
  }
  onBeforeUnmount(() => {
    dispose(contributionBoardChartRef.value as HTMLDivElement)
  })

  defineExpose({ refreshData })
</script>
<style lang="less" scoped>
  .ad-chart-w {
    margin-top: 10px;
    background-color: #fff;
    padding: 20px;
    position: relative;
  }
  .all-target {
    width: 220px;
    border: 1px solid var(--color-border);
    height: 80px;
    padding: 10px 5px 10px 10px;
    position: relative;
    font-size: 12px;
    line-height: 20px;
    margin-bottom: 10px;
    .value-price {
      font-size: 16px;
      font-weight: bold;
      margin-right: 8px;
    }
    .line {
      position: absolute;
      width: 100%;
      left: 0;
      top: 0;
      height: 2px;
    }
    .price-item {
      .label {
        margin-right: 5px;
      }
      .val {
        margin-right: 5px;
      }
      .arco-icon {
        font-size: 18px;
      }
    }
    .diff {
      margin-left: 5px;
    }
  }
  .type-w {
    position: absolute;
    top: 15px;
    right: 20px;
  }

  :deep(.arco-radio-group-button) {
    padding: 0;
    .arco-radio-button {
      margin: 0;
      background-color: #fff;
      line-height: 26px;
      border: 1px solid var(--color-border);
      &:first-child {
        border-radius: 4px 0 0 4px;
      }
      &:last-child {
        border-radius: 0 4px 4px 0;
      }
    }
    .arco-radio-checked {
      border-color: rgb(var(--primary-6));
    }
  }
  .chart-w {
    height: 350px;
    flex: 1;
    width: 100%;
  }
</style>
